package com.bmslz.monitor.base.interceptor;

import com.bmslz.monitor.base.CommonConstant;
import com.bmslz.monitor.base.config.excep.MyException;
import com.bmslz.monitor.base.entity.User;
import com.bmslz.monitor.helper.JwtHelper;
import com.bmslz.monitor.helper.LoginHelper;
import com.bmslz.monitor.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null) {
            LoginHelper.remove();
            throw new MyException(401, "登录失效");
        }
        try {
            Claims claims = JwtHelper.getClaimsVyToken(token);
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap map = objectMapper.readValue(claims.getSubject(), HashMap.class);
            System.out.println("claims = " + claims);
            User user = userService.queryUserByUsername((String) map.get(CommonConstant.USERNAME));

            if (user == null) {
                throw new MyException(401, "登录失效");
            }
            LoginHelper.setUser(user);
            return true;
        } catch (Exception e) {
            LoginHelper.remove();
            throw new MyException(401, "登录失效");
        }
    }
}
